/*
 * @Author: your name
 * @Date: 2020-08-10 11:14:36
 * @LastEditTime: 2020-09-23 16:13:12
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \devopsh:\project\QMangolia-web\src\store\modules\permission.js
 */
import { asyncRoutes, constantRoutes } from '@/router'
import store from '../index';

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      // 超级管理员拥有所有的权限
      if (store.getters.roleId === 1) {
        res.push(tmp)
      } else {
        // 隐藏的菜单 全部加入权限
        if (tmp.hidden === true) {
          res.push(tmp)
        } else {
          // 非隐藏的 即列表 判断权限
          if (in_array(tmp.bPath, roles) === true) {
            res.push(tmp)
          }
        }
      }
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      let accessedRoutes
      const nodes = store.getters.Nodes
      accessedRoutes = filterAsyncRoutes(asyncRoutes, nodes.split(','))
      commit('SET_ROUTES', accessedRoutes)
      resolve(state.routes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

function in_array(search, array) {
  for (var i in array) {
    if (array[i] === search) {
      return true;
    }
  }
  return false;
}
